package com.cq.controller;

import com.cq.pojo.Admin;
import com.cq.pojo.Result;
import com.cq.pojo.Role;
import com.cq.service.AdminService;
import com.cq.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Author: 悠久的苍穹
 * @Date: 2021/1/14 15:21
 * @Description: 管理员控制层
 * @Version: 1.0
 */
@Controller
public class AdminController {

    @Autowired
    AdminService adminService;
    @Autowired
    RoleService roleService;
    @Autowired
    HttpSession session;

    @PostMapping(value = "/admin/updateAdmin")
    @ResponseBody
    public Result updateAdmin(@RequestBody Map<String,Object> map){
        Result result = new Result();
        Integer id = Integer.parseInt(map.get("id").toString());
        String name = map.get("name").toString();
        String email = map.get("email").toString();
        String sex = map.get("sex").toString();
        String img = map.get("img").toString();
        String phone = map.get("phone").toString();
        Integer role_id = Integer.parseInt(map.get("role_id").toString());
        String role = map.get("role").toString();
        Admin admin = new Admin();
        admin.setId(id);
        admin.setName(name);
        admin.setEmail(email);
        admin.setSex(sex);
        admin.setImg(img);
        admin.setPhone(phone);
        int i = adminService.updateAdmin(admin);
        int j = roleService.updateAdminRole(id,Integer.parseInt(role));
        if(i==1&&j==1){
//            session.setAttribute("admin",adminService.findAdminById(id));
//            session.setAttribute("role",roleService.findRoleByAdminId(id));
            Subject subject = SecurityUtils.getSubject();
            subject.getSession().setAttribute("admin", adminService.findAdminByName(name));
            result.setCode(200);
            result.setMsg("修改成功");
        }else{
            result.setCode(500);
            result.setMsg("修改失败");
        }
        return result;
    }

    @ResponseBody
    @PutMapping(value = "/admin/updatePassword", produces = "application/json;charset=UTF-8")
    public Result updatePassword(@RequestBody Map<String, Object> map) {
        Result result = new Result();
        String oldPassword = map.get("oldPassword").toString();
        String password = map.get("password").toString();
//        Admin admin = (Admin) session.getAttribute("admin");
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getSession().getAttribute("admin");
        System.out.println(admin);
        if (adminService.findAdminByPassword(admin.getName(),DigestUtils.md5DigestAsHex(oldPassword.getBytes())) != null){
            int i = adminService.updatePassword(DigestUtils.md5DigestAsHex(password.getBytes()),admin.getId());
            if (i == 1) {
                Admin admin2 = adminService.findAdminById(admin.getId());
//                session.setAttribute("admin",admin2);
                subject.getSession().setAttribute("admin",admin2);
                result.setCode(200);
            } else {
                result.setCode(500);
                result.setMsg("后台出错");
            }
        }else{
            result.setCode(500);
            result.setMsg("密码不正确！");
        }
        return result;
    }

    @GetMapping("/getAdmins")
    @ResponseBody
    public Result getAdmins(@RequestParam int page,
                            @RequestParam int limit) {
        Result result = new Result();
        int count = adminService.getCount();
        List<Admin> admin= adminService.findAllAdmin(page, limit);
        result.setCount(count);
        result.setData(admin);
        result.setCode(0);
        return result;
    }
    @GetMapping("/getAdminsByRoleId")
    @ResponseBody
    public Result getAdmins(@RequestParam int role_id,
                            @RequestParam int page,
                            @RequestParam int limit) {
        Result result = new Result();
        int count = adminService.getCount();
        List<Admin> admin= adminService.findAllAdminByRoleId(role_id,page, limit);
        System.out.println(admin);
        result.setCount(count);
        result.setData(admin);
        result.setCode(0);
        return result;
    }

    @PostMapping("/addAdmin")
    @ResponseBody
    public Result addAdmin(@RequestBody Map<String, Object> map){
        Result result = new Result();
        Integer role_id = Integer.parseInt(map.get("role").toString());
        String name = map.get("name").toString();
        String sex = map.get("sex").toString();
        String img = map.get("img").toString();
        String phone = map.get("phone").toString();
        String email = map.get("email").toString();
        Admin admin = new Admin();
        admin.setName(name);
//        admin.setPassword("123456");
        admin.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        admin.setEmail(email);
        admin.setSex(sex);
        admin.setImg(img);
        admin.setPhone(phone);
        int i = adminService.addAdmin(admin);
        int j = roleService.addAdminRole(adminService.findAdminByName(name).getId(),role_id);
        if(i==1&&j==1){
            result.setCode(200);
        }else {
            result.setCode(500);
        }
        return result;
    }

    @GetMapping("/editAdminUI/{id}")
    public String editAdminUI(@PathVariable("id") int id, Model model){
        Admin admin = adminService.findAdminById(id);
        Role role = roleService.findRoleByAdminId(admin.getId());
        model.addAttribute("adm",admin);
        model.addAttribute("role",role);
        return "user/administrators/adminform";
    }

    @ResponseBody
    @GetMapping("/checkAdminName")
    public Result checkAdminName( @RequestParam String name) {
        Result result = new Result();
        Admin admin = adminService.findAdminByName(name);
        if (admin != null) {
            result.setCode(200);
        } else {
            result.setCode(500);
        }
        return result;
    }

    @DeleteMapping("/delAdmin/{id}")
    @ResponseBody
    public Result moreLog(@PathVariable("id") String id) {
        Result result = new Result();
        String[] s = id.split(",");
        for (int i = 0; i < s.length; i++) {
            roleService.deleteRoleById(Integer.parseInt(s[i]));
            adminService.deleteAdminById(Integer.parseInt(s[i]));
        }
        result.setCode(200);
        return result;
    }

}
